<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { useRoute } from "vue-router";
  import axios from '@/utils/axios';
  import { showToast } from "vant";
  import WangEditor from "wangeditor";
  import {client} from "@/utils/alioss.ts";

  const route = useRoute();
  let instance;
  const editor = ref(null)

  // 响应式数据
  const showRepliesCount = ref<Record<number, number>>({});
  const showAllReplies = ref<Record<number, boolean>>({});
  const isLoading = ref(false);

  const data = reactive({
    token: '',
    showAdd: false,
    addForm:{
      postId:0,//帖子id
      content: '',//内容
      parentCommentId:'',//二级评论id
    },
    post: {
      postId: 0,
      comments: [] as Array<{
        commentId: number;
        user: { avatar: string; nickname: string };
        createTime: string;
        content: string;
        parentComments: Array<{
          commentId: number;
          user: { nickname: string };
          content: string;
          createTime: string;
        }>;
      }>
    }
  });

  const loadDialog = ()=>{
    initEditor();
  }
  const destroyEditor = () =>{
    instance.destroy()
    instance = null
  }
  const initEditor = () => {
    instance = new WangEditor(editor.value)
    instance.config.showLinkImg = false
    instance.config.showLinkImgAlt = false
    instance.config.showLinkImgHref = false
    instance.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
    instance.config.uploadFileName = 'file'
    instance.config.uploadImgHeaders = {
      token: "234"
    }
    instance.config.uploadImgHooks = {
      customInsert: function (insertImgFn, result) {
        if (result.data && result.data.length) {
          result.data.forEach(item => insertImgFn(item))
        }
      }
    }

    instance.config.uploadImgServer = "";

    instance.config.customUploadImg = function (resultFiles, insertImgFn) {

      resultFiles.forEach(file => {
        var fileName = 'abc/'+'banner' + `${Date.parse(new Date())}` + file.name;
        client().put(fileName, file).
        then((res)=>{
          insertImgFn(res.url);
        })

      });
    };


    Object.assign(instance.config, {
      onchange() {
        console.log('change')
      },
    })
    instance.create();
  }

  // 初始化回复显示状态
  const initReplyDisplay = () => {
    // 添加安全检查
    if (data.post.comments && Array.isArray(data.post.comments)) {
      data.post.comments.forEach(comment => {
        showRepliesCount.value[comment.commentId] = 2;
        showAllReplies.value[comment.commentId] = false;
      });
    }
  };

  // 获取评论数据
  const fetchComments = async () => {
    try {
      isLoading.value = true;
      const postId = route.params.postId;
      const res = await axios.post(`/api/hotStop/getByPostId/${postId}`);

      // 添加空值检查
      if (res.data && res.data.comments) {
        data.post = res.data;
        initReplyDisplay();
      } else {
        // 设置默认值
        data.post = {
          postId: 0,
          comments: []
        };
      }
    } catch (err) {
      console.error("获取评论失败:", err);
      showToast("加载评论失败，请重试");
      // 出错时设置默认值
      data.post = {
        postId: 0,
        comments: []
      };
    } finally {
      isLoading.value = false;
    }
  };

  // 时间格式化函数
  const formatTime = (timestamp: string): string => {
    const now = new Date();
    const postTime = new Date(timestamp);
    const diffInHours = (now.getTime() - postTime.getTime()) / (1000 * 60 * 60);

    if (diffInHours < 1) {
      return `${Math.floor(diffInHours * 60)}分钟前`;
    }
    if (diffInHours < 24) {
      return `${Math.floor(diffInHours)}小时前`;
    }
    if (diffInHours < 48) {
      return `昨天 ${postTime.getHours().toString().padStart(2, '0')}:${postTime.getMinutes().toString().padStart(2, '0')}`;
    }
    if (postTime.getFullYear() === now.getFullYear()) {
      return `${postTime.getMonth() + 1}-${postTime.getDate()}`;
    }
    return `${postTime.getFullYear()}-${postTime.getMonth() + 1}-${postTime.getDate()}`;
  };

  // 处理显示更多回复
  const showMoreReplies = (commentId: number) => {
    const comment = data.post.comments.find(c => c.commentId === commentId);
    if (!comment) return;

    const totalReplies = comment.parentComments.length;
    const currentCount = showRepliesCount.value[commentId] || 2;

    if (currentCount >= totalReplies) {
      showRepliesCount.value[commentId] = 2;
      showAllReplies.value[commentId] = false;
    } else {
      const newCount = Math.min(currentCount + 10, totalReplies);
      showRepliesCount.value[commentId] = newCount;
      showAllReplies.value[commentId] = newCount >= totalReplies;
    }
  };

  // 获取可见回复
  const getVisibleReplies = (replies: any[], commentId: number) => {
    const count = showRepliesCount.value[commentId] || 2;
    return replies.slice(0, count);
  };

  // 获取按钮文本
  const getButtonText = (commentId: number, totalReplies: number) => {
    const currentCount = showRepliesCount.value[commentId] || 2;
    return currentCount >= totalReplies
        ? '收起回复'
        : `查看更多回复 (${Math.min(10, totalReplies - currentCount)})`;
  };

  // 处理头像加载错误
  const handleAvatarError = (event: Event) => {
    const target = event.target as HTMLImageElement;
    // 检查是否已经设置过默认头像，避免无限循环
    if (!target.src.includes('default')) {
      target.src = '/default-avatar.png';
    }
  };

  onMounted(() => {
    fetchComments();
  });

  const ParentCommentIdShow = (commentId) => {
    data.addForm.parentCommentId = commentId;
    data.showAdd = true;
  }

  const doAdd = () => {
    // 确保获取到编辑器的最新内容
    if (instance) {
      console.log("编辑器内容：", instance.txt.html());
      data.addForm.content = instance.txt.html();
      data.addForm.postId = data.post.postId;
    }

    const url = "/api/hotStop/commentsadd";
    axios.post(url, data.addForm)
        .then(res => {
          console.log("data.addForm",data.addForm);
          data.showAdd = false;
          fetchComments();
        })
  };
</script>

<template>
  <div class="comment-container">
    <!-- 评论头部 -->
    <div class="comment-header">
      <div class="comment-count">
        <span>评论 {{ data.post.comments.length }}</span>
        <van-divider class="header-divider" />
      </div>
    </div>

    <!-- 加载状态 -->
    <van-loading v-if="isLoading" class="loading" type="spinner" color="#1989fa" />

    <!-- 评论列表 -->
    <div v-else class="comments-list">
      <div
          v-for="(comment, index) in data.post.comments"
          :key="comment.commentId"
          class="comment-item"
          :class="{ 'last-item': index === data.post.comments.length - 1 }"
      >
        <!-- 用户信息 -->
        <div class="comment-user-info">
          <img
              :src="comment.user.avatar || '/default-avatar.png'"
              alt="用户头像"
              class="user-avatar"
              @error="handleAvatarError"
          >
          <div class="user-details">
            <div class="user-name">{{ comment.user.nickname || '匿名用户' }}</div>
            <div class="user-meta">
              <span>{{ formatTime(comment.createTime) }} · 上海</span>
            </div>
          </div>
        </div>

        <!-- 评论内容 -->
        <div class="comment-content" @click="ParentCommentIdShow(comment.commentId)">
          <p v-html="comment.content"></p>
        </div>

        <!-- 二级评论 -->
        <div v-if="comment.parentComments && comment.parentComments.length > 0" class="replies-list">
          <div
              v-for="(reply, replyIndex) in getVisibleReplies(comment.parentComments, comment.commentId)"
              :key="reply.commentId"
              class="reply-item"
              :class="{ 'last-reply': replyIndex === getVisibleReplies(comment.parentComments, comment.commentId).length - 1 }"
          >
            <div class="reply-content">
              <span class="reply-name">{{ reply.user.nickname }}:</span>
              <span v-html="reply.content" class="reply-text" @click="ParentCommentIdShow(comment.commentId)"></span>
            </div>
            <div class="reply-meta">
              <span>{{ formatTime(reply.createTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 查看全部回复按钮 -->
        <div
            v-if="comment.parentComments && comment.parentComments.length > 2"
            class="show-all-replies"
            @click="showMoreReplies(comment.commentId)"
        >
          <span class="reply-btn">{{ getButtonText(comment.commentId, comment.parentComments.length) }}</span>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="data.post.comments.length === 0" class="empty-comments">
        <van-empty description="暂无评论，快来抢沙发吧~" />
      </div>
    </div>
  </div>

  <el-dialog @open="loadDialog" @closed="destroyEditor" :close-on-click-modal="false" v-model="data.showAdd" style="width: 100%;height: 70%;">
    <el-form label-width="120">
      <el-form-item>
        <div ref="editor" ></div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doAdd">确认</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<style scoped>
  .comment-container {
    padding: 15px;
    background-color: #fff;
  }

  .comment-header {
    margin-bottom: 15px;
  }

  .comment-count {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }

  .header-divider {
    margin: 10px 0;
    background-color: #f5f5f5;
  }

  .loading {
    display: flex;
    justify-content: center;
    padding: 30px 0;
  }

  .comments-list {
    margin-bottom: 20px;
  }

  .comment-item {
    padding: 15px;
    margin-bottom: 12px;
    border-radius: 12px;
    background-color: #fafafa;
    transition: background-color 0.2s;
  }

  .comment-item:hover {
    background-color: #f5f5f5;
  }

  .comment-item.last-item {
    margin-bottom: 0;
  }

  .comment-user-info {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }

  .user-avatar {
    width: 42px;
    height: 42px;
    border-radius: 50%;
    margin-right: 12px;
    object-fit: cover;
    border: 1px solid #eee;
  }

  .user-details {
    flex: 1;
  }

  .user-name {
    font-size: 15px;
    font-weight: 500;
    color: #333;
    margin-bottom: 3px;
  }

  .user-meta {
    font-size: 12px;
    color: #999;
    display: flex;
    gap: 8px;
  }

  .location::before {
    content: "·";
    margin-right: 4px;
  }

  .comment-content {
    font-size: 15px;
    line-height: 1.6;
    color: #333;
    margin-bottom: 10px;
    padding-left: 54px; /* 与头像对齐 */
  }

  .comment-actions {
    display: flex;
    gap: 15px;
    padding-left: 54px;
    margin-bottom: 10px;
  }

  .action-item {
    font-size: 13px;
    color: #666;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 4px;
    transition: color 0.2s;
  }

  .action-item:hover {
    color: #1989fa;
  }

  .replies-list {
    padding: 10px 0 5px 54px;
    border-top: 1px dashed #eee;
    margin-top: 5px;
  }

  .reply-item {
    padding: 8px 0;
    border-bottom: 1px dashed #f0f0f0;
  }

  .reply-item.last-reply {
    border-bottom: none;
  }

  .reply-content {
    display: flex;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 4px;
  }

  .reply-name {
    color: #3B82F6;
    font-weight: 500;
    margin-right: 6px;
  }

  .reply-text {
    display: inline;
    color: #555;
  }

  .reply-text :deep(p) {
    display: inline;
    margin: 0;
    padding: 0;
  }

  .reply-meta {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #999;
  }

  .reply-action {
    cursor: pointer;
    transition: color 0.2s;
  }

  .reply-action:hover {
    color: #1989fa;
  }

  .show-all-replies {
    padding-left: 54px;
    margin-top: 8px;
  }

  .reply-btn {
    font-size: 13px;
    color: #3B82F6;
    cursor: pointer;
    display: inline-block;
    padding: 3px 0;
    transition: all 0.2s;
  }

  .reply-btn:hover {
    color: #1D4ED8;
    text-decoration: underline;
  }

  .empty-comments {
    padding: 40px 0;
    text-align: center;
  }
</style>